﻿#include "TextInSceneWidget.h"
#include "ui_TextInSceneWidget.h"

#include <QFileDialog>
#include <QFile>
#include <QFileInfo>
#include <QTextCodec>
#include <QTextStream>
#include <QByteArray>
#include <QByteArrayList>
#include <QDebug>
#include <QTextBlock>

#include "GlobalDefine.h"

class TextInSceneWidget::TextInSceneWidgetPrivate :public QObject, public AstScene
{
public:
	QString label_name;
public:
	TextInSceneWidgetPrivate(QObject*parent) :QObject(parent)
	{}

	virtual int type() override
	{
		return AstScene::SCENE_IN;
	}
	virtual QString typeName() override
	{
		return "TextInScene";
	}
	virtual QString label()
	{
		return label_name;
	}
	virtual void setLabel(const QString&s)
	{
		label_name = s;
	}
	virtual QWidget* widget() override
	{
		return qobject_cast<QWidget*>(parent());
	}
	virtual void onOpening() override
	{}
	virtual void onClosing() override
	{}

};

TextInSceneWidget::TextInSceneWidget(QWidget *parent)
	: QWidget(parent), private_ptr(new TextInSceneWidgetPrivate(this))
{
	ui = new Ui::TextInSceneWidget();
	ui->setupUi(this);

	QByteArrayList lst = QTextCodec::availableCodecs();
	for each(auto a in lst) {
		ui->cbx_code->insertItem(0, a);
	}
}

TextInSceneWidget::~TextInSceneWidget()
{
	delete ui;
}

void TextInSceneWidget::on_btn_select_clicked()
{
	QString filename = QFileDialog::getOpenFileName(this, QStringLiteral("选择文件"), ".", "*.*");
	ui->edt_filename->setText(filename);

	//ui->txt_in
}
void TextInSceneWidget::on_btn_load_clicked()
{
	QString filename = ui->edt_filename->text().trimmed();
	if (filename.isEmpty())
		return;

	int maxrows = ui->edt_maxrows->text().toInt();

	QFileInfo fi(filename);

	//PRINT_OUTPUT(QStringLiteral("准备加载文件【%1】").arg(filename));

	if (!fi.isReadable()) {
		//PRINT_OUTPUT(QStringLiteral("加载失败，文件【%1】不可读").arg(filename));
		return;
	}

	int count = 0;
	QFile f(filename);
	if (!f.open(QIODevice::OpenModeFlag::ReadOnly)) {
		//PRINT_OUTPUT(QStringLiteral("加载失败：%1，文件【%2】").arg(f.errorString()).arg(filename));
		return;
	}

	QString code_name = ui->cbx_code->currentText();

	QTextCodec*code = nullptr;
	if (!code_name.isEmpty())
		code = QTextCodec::codecForName(code_name.toLocal8Bit());
	if (!code)
		code = QTextCodec::codecForLocale(); //QTextCodec::codecForName("UTF-8");

	QTextStream in(&f);
	in.setCodec(code);

	QString txt;
	if (maxrows) {
		QString line;
		while (maxrows && in.readLineInto(&line)) {

			if (!txt.isEmpty()) {
				txt += "\n";
			}
			txt += line;

			maxrows--;
		}
		//qDebug() << "maxrows:" << maxrows;
	}
	else {
		txt = in.readAll();
	}
	ui->txt_in->setPlainText(txt);
}

AstScene* TextInSceneWidget::operator()()
{
	return dynamic_cast<AstScene*>(private_ptr);
}
QTextDocument* TextInSceneWidget::textDocument()
{
	return ui->txt_in->document();
}
